import dayjs from "dayjs";
import utc from 'dayjs/plugin/utc';
import duration from 'dayjs/plugin/duration';
import router from "@system.router";
import { checkAuthorization,listEventLog, monthEventLog } from "../../service";

dayjs.extend(utc);
dayjs.extend(duration);
const TAG = '[MY_TAG]';

async function plus(params) {
  try {
    const action = {};
    action.bundleName = "com.sengmitnick.timelogger";
    action.abilityName = "com.sengmitnick.timelogger.PlusAbility";
    action.data = params;
    action.messageCode = 1001;
    action.abilityType = 0;

    var result = await FeatureAbility.startAbility(action);
    console.info('plus result is:' + JSON.stringify(result));
  } catch (err) {
    console.error('plus failed. Cause: ' + err.toString());
  }
  return
}

export default {
  data: {
    active: "",
    tabs: [],
    loading: false,
    brushList: [],
    dateList: []
  },
  onInit() {
    // "stream", "budget",
    this.tabs = ["diagram", "setting"].map((item) => {
      let icon = item;
      if (item === "diagram") icon = "chart";
      return {
        icon,
        name: item,
        uri: `pages/${item}/${item}`,
        text: this.$t(`tabs.${item}`),
      };
    });
    checkAuthorization().then(() => {
      const curDate = new Date().getFullYear() + '/' + (new Date().getMonth() + 1) + '/01'
      this.monthEventLog(curDate);
    })
  },
  // 选择日期
  async chooseDay(e) {
    this.getBrushList(e.detail);
  },
  // 改变月份
  changeMonth(e) {
    this.brushList = []
    this.monthEventLog(e.detail);
  },
  itemClick(e) {
    const { name } = e.detail;
    const item = this.tabs.find((tab) => tab.name === name);
    if (item) {
      router.push({ uri: item.uri });
    }
  },
  async getBrushList(date) {
    if (this.loading) return;
    this.loading = true
    this.brushList = []
    console.info(TAG + "getBrushList: " + date)
    await this.listEventLog(date)
    this.loading = false
  },
  async listEventLog(startAt) {
    const result = await listEventLog({pageSize: 1000,query: { startAt }})
    this.brushList = result.map(item => {
      const startAt = dayjs(item.startAt);
      const endAt = item.endAt ?  dayjs(item.endAt) : null;
      let duration = '进行中';
      if (endAt) {
        duration = dayjs.duration(endAt.diff(startAt)).format("HH:mm:ss")
      }
      return {
        name: item.name,
        icon: item.icon,
        color: item.color ?? '#ED6F21',
        time:  startAt.format("HH:mm:ss"),
        duration
      }
    });
  },
  async monthEventLog(month) {
    if (this.loading) return;
    this.loading = true
    const list = await monthEventLog({month})
    this.dateList = list.map(({date}) => date)
    await this.listEventLog(month)
    console.info(TAG + JSON.stringify(this.dateList))
    this.loading = false
  },
};
